package com.juxing.webserver;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.juxing.service.accountCenter.IAccountCenterService;
import com.juxing.service.accountCenter.bean.UserAccessTokenBean;
import com.juxing.service.userCenter.IUserCenterService;
import com.juxing.service.userCenter.bean.UserBean;
import com.juxing.webserver.common.ReturnCodeConstant;

/**
 * 全局Filter
 * 
 * @author liuql
 *
 */
public class WebFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(WebFilter.class);

	@Autowired
	private IUserCenterService userCenterService;
	@Autowired
	private IAccountCenterService accountCenterService;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request; 
		
		//打印请求详细
		this.printRequestDetails(req);
		
		String uri = req.getRequestURI();
		if("/favicon.ico".equals(uri)) {
			chain.doFilter(request, response);
			return;
		}
		if(uri.endsWith(".json")) {
			response.setContentType("application/json;charset=UTF-8");
		}
		try{
			if (!uri.startsWith("/front/")) {// 前端无需鉴权的接口
				int userId = Integer.parseInt(req.getParameter("userId"));
				if (userId <= 0) {
					this.outputError(request, response, ReturnCodeConstant.USER_NOT_EXIST);
					return;
				}
				UserBean user = userCenterService.queryByUserId(userId);
				if (user == null) {
					this.outputError(request, response, ReturnCodeConstant.USER_NOT_EXIST);
					return;
				}
				UserAccessTokenBean accountToken = accountCenterService.queryUserAccountByUserId(userId);
				//将用户对象添加到request中
				request.setAttribute(Constant.CURR_USER, user);
				request.setAttribute(Constant.CURR_ACCOUNT_TOKEN, accountToken);
			}
			chain.doFilter(request, response);
			//将用户对象从request中移出
			request.removeAttribute(Constant.CURR_USER);
			request.removeAttribute(Constant.CURR_ACCOUNT_TOKEN);
		} catch(Exception e) {
			logger.error("error", e);
			this.outputError(request, response, ReturnCodeConstant.SERVER_ERROR);
		}
		
	}

	/**
	 * 输出错误页面
	 * 
	 * @param req
	 * @param res
	 * @param errorCode
	 */
	public void outputError(ServletRequest request, ServletResponse response,
			String errorCode) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request; 
		String uri = req.getRequestURI();
		if(uri.endsWith(".json")) {
			JSONObject outObj = new JSONObject();
			outObj.put("code", errorCode);
			String errMsg = ReturnCodeConstant.getErrorMsg(errorCode);
			if(errMsg == null) {
				errMsg = "";
			}
			outObj.put("errMsg", errMsg);
//			response.setContentType("text/html;charset=UTF-8"); 
			response.setContentType("application/json;charset=UTF-8");
			response.getOutputStream().write(outObj.toJSONString().getBytes());
		} else {//待补充
			logger.warn("error no handler.");
		}
	}

	/**
	 * 打印访问详细
	 * @param request
	 */
	private void printRequestDetails(HttpServletRequest request) {
		if(!logger.isDebugEnabled()) {
			return;
		}
		StringBuilder paramInfoBuilder = new StringBuilder();
		paramInfoBuilder.append("\n").append(request.getRequestURI());
		@SuppressWarnings("rawtypes")
		Enumeration enums = request.getParameterNames();
		if(enums != null) {
			while(enums.hasMoreElements()) {
				String paramName = (String)enums.nextElement();
				String paramValue = request.getParameter(paramName);
				paramInfoBuilder.append("\n").append(paramName).append("=").append(paramValue);
			}
		}
		paramInfoBuilder.append("\n");
		logger.debug(paramInfoBuilder.toString());
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}
	@Override
	public void destroy() {

	}
}
